package nancal.mp.web.sys

import io.swagger.annotations.ApiOperation
import nancal.mp.db.mongo.entity.admin.AdminPermissionPageAction
import nancal.mp.db.mongo.entity.admin.AdminUser
import nancal.mp.db.mongo.mor
import nbcp.base.annotation.Require
import nbcp.base.comm.ApiResult
import nbcp.base.comm.JsonResult
import nbcp.base.db.LoginUserModel
import nbcp.base.utils.Md5Util
import nbcp.mvc.sys.LoginUser
import nbcp.mvc.sys.UserId
import nbcp.myoql.db.mongo.query
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.time.LocalDate
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by udi on 17-5-23.
 */
@RestController
@RequestMapping("/sys")
class LoginInfo_Controller {

    class LoginModel : AdminUser()


    @ApiOperation(value = "获取登录者信息")
    @PostMapping("/getMine")
    fun getMine(
        loginUser: LoginUserModel,
        response: HttpServletResponse
    ): ApiResult<AdminUser> {
        var usr = mor.admin.adminUser.query().where { it.id mongoEquals loginUser.id }.toEntity(LoginModel::class.java)
        if (usr == null) {
            response.status = 401;
            return ApiResult.error("找不到用户信息")
        }

        return ApiResult.of(usr);
    }

    @PostMapping("/reset-password")
    fun resetPwd(
        oldPassword: String,
        @Require newPassword: String,
        request: HttpServletRequest,
        loginUser: LoginUserModel
    ): JsonResult {
        if (oldPassword == newPassword) return JsonResult.error("新老密码不能相同")

        var loginUser = mor.admin.adminLoginUser.queryById(request.UserId)
            .toEntity();

        if (loginUser == null) {
            return JsonResult.error("找不到用户信息")
        }

        if (loginUser.password != Md5Util.getBase64Md5(oldPassword)) {
            return JsonResult.error("密码不正确")
        }

        var defaultPassword = Md5Util.getBase64Md5(newPassword);
        mor.admin.adminLoginUser.updateById(request.UserId)
            .set { it.password to defaultPassword }
            .exec()

        if (mor.affectRowCount > 0) {
            return JsonResult();
        } else return JsonResult.error("修改密码失败")
    }


    @PostMapping("/reset-mfa1")
    fun setMfa1(
        oldPassword: String,
        @Require mfa1: String,
        @Require mfa1ExpireAt: LocalDate,
        request: HttpServletRequest,
        loginUser: LoginUserModel
    ): JsonResult {

        var loginUser = mor.admin.adminLoginUser.queryById(request.UserId)
            .toEntity();

        if (loginUser == null) {
            return JsonResult.error("找不到用户信息")
        }

        if (loginUser.password != Md5Util.getBase64Md5(oldPassword)) {
            return JsonResult.error("密码不正确")
        }

        mor.admin.adminLoginUser.updateById(request.UserId)
            .set { it.mfa1 to mfa1 }
            .set { it.mfa1ExpireAt to mfa1ExpireAt }
            .exec()

        if (mor.affectRowCount > 0) {
            return JsonResult();
        } else return JsonResult.error("修改密码失败")
    }


    @PostMapping("/get-ans")
    fun getAns(request: HttpServletRequest): MutableMap<String, Set<String>> {
        var roles = mor.admin.adminRole.query()
            .where { it.id mongoIn request.LoginUser.roles }
            .toList()

        var ret = mutableMapOf<String, Set<String>>();

        var setOnePageAction: (Map.Entry<String, List<AdminPermissionPageAction>>) -> Unit = {
            var ori_value = ret.get(it.key) ?: setOf();
            ret.put(it.key, (ori_value + it.value.map { it.action }).toSet())

        }

        var setOneRoleItem: (MutableList<AdminPermissionPageAction>) -> Unit = {
            it.groupBy { it.page.path }.forEach {
                setOnePageAction(it);
            }
        }

        roles.forEach {
            setOneRoleItem(it.pageActions)
        }

        return ret
    }

}

